import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Popconfirm, Badge, Dropdown, Menu, Modal, Form, Input, Select, InputNumber, Space, Tag, Tooltip, Drawer, Divider } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SettingOutlined, DownOutlined, UploadOutlined, HistoryOutlined, ExportOutlined, ImportOutlined, TeamOutlined } from '@ant-design/icons';
import { getDeviceList, createDevice, updateDevice, deleteDevice, updateDeviceStatus, getDeviceTypeOptions, getDeviceStatusOptions, getStores, getVenues } from '@/services/device.js';
import { getDeviceGroupList, getGroupsByDevice, addDevicesToGroup, removeDevicesFromGroup, getDeviceGroupDetail } from '@/services/deviceGroup';

const DeviceList = () => {
  const [createModalVisible, setCreateModalVisible] = useState(false);
  const [updateModalVisible, setUpdateModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState({});
  const [form] = Form.useForm();
  const actionRef = useRef();
  const [stores, setStores] = useState([]);
  const [venues, setVenues] = useState([]);
  const [selectedStoreId, setSelectedStoreId] = useState(null);
  const [filteredVenues, setFilteredVenues] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [logDrawerVisible, setLogDrawerVisible] = useState(false);
  const [deviceLogs, setDeviceLogs] = useState([]);
  const [currentDeviceId, setCurrentDeviceId] = useState(null);
  const [deviceGroupsVisible, setDeviceGroupsVisible] = useState(false);
  const [currentDeviceGroups, setCurrentDeviceGroups] = useState([]);
  const [allGroups, setAllGroups] = useState([]);
  const [deviceGroupsLoading, setDeviceGroupsLoading] = useState(false);
  const [deviceGroupsMap, setDeviceGroupsMap] = useState({});

  // 扩展设备类型选项
  const deviceTypeOptions = [
    { label: '门禁', value: 0 },
    { label: '网关', value: 1 },
  ];
  
  // 设备状态选项
  const deviceStatusOptions = getDeviceStatusOptions();
  
  // 获取门店和场地数据
  useEffect(() => {
    const fetchStoresAndVenues = async () => {
      try {
        const storesResponse = await getStores();
        if (storesResponse.success) {
          setStores(storesResponse.data.list || []);
        }
        
        const venuesResponse = await getVenues();
        if (venuesResponse.success) {
          setVenues(venuesResponse.data.list || []);
        }
      } catch (error) {
        console.error('获取门店或场地数据失败:', error);
        message.error('获取门店或场地数据失败');
      }
    };
    
    fetchStoresAndVenues();
  }, []);
  
  // 处理门店选择变化
  const handleStoreChange = (storeId) => {
    setSelectedStoreId(storeId);
    if (storeId) {
      const storeVenues = venues.filter(venue => venue.store_id === storeId);
      setFilteredVenues(storeVenues);
      // 如果切换了门店，清空之前选择的场地
      form.setFieldsValue({ venue_id: undefined });
    } else {
      setFilteredVenues([]);
    }
  };

  // 查看设备日志
  const handleViewLogs = async (deviceId) => {
    setCurrentDeviceId(deviceId);
    // 这里应该调用获取设备日志的API
    // 模拟数据
    const mockLogs = [
      { id: 1, device_id: deviceId, action: '状态变更', detail: '设备状态由离线变为正常', created_at: new Date().getTime() / 1000 - 3600 * 2 },
      { id: 2, device_id: deviceId, action: '配置更新', detail: '更新固件版本至1.2.3', created_at: new Date().getTime() / 1000 - 3600 * 24 },
      { id: 3, device_id: deviceId, action: '重启设备', detail: '管理员操作', created_at: new Date().getTime() / 1000 - 3600 * 48 },
    ];
    setDeviceLogs(mockLogs);
    setLogDrawerVisible(true);
  };

  // 处理批量删除
  const handleBatchDelete = async () => {
    try {
      if (selectedRowKeys.length === 0) {
        message.warning('请选择需要删除的设备');
        return;
      }
      
      Modal.confirm({
        title: '确认删除',
        content: `确定要删除选中的 ${selectedRowKeys.length} 个设备吗？此操作不可恢复。`,
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
          // 这里应该调用批量删除API，这里模拟单个删除
          const promises = selectedRowKeys.map(id => deleteDevice(id));
          await Promise.all(promises);
          
          message.success(`成功删除 ${selectedRowKeys.length} 个设备`);
          setSelectedRowKeys([]);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      });
    } catch (error) {
      message.error('批量删除设备失败');
    }
  };

  // 处理批量状态更新
  const handleBatchUpdateStatus = async (status) => {
    try {
      if (selectedRowKeys.length === 0) {
        message.warning('请选择需要更新状态的设备');
        return;
      }
      
      // 这里应该调用批量更新状态API，这里模拟单个更新
      const promises = selectedRowKeys.map(id => updateDeviceStatus(id, status));
      await Promise.all(promises);
      
      message.success(`成功更新 ${selectedRowKeys.length} 个设备状态`);
      setSelectedRowKeys([]);
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('批量更新设备状态失败');
    }
  };

  // 状态标签渲染
  const renderStatusBadge = (status) => {
    const statusMap = {
      0: { status: 'default', text: '离线' },
      1: { status: 'success', text: '正常' },
      2: { status: 'error', text: '故障' },
    };
    const { status: badgeStatus, text } = statusMap[status] || statusMap[0];
    return <Badge status={badgeStatus} text={text} />;
  };

  // 处理创建设备
  const handleCreate = async (values) => {
    try {
      await createDevice(values);
      message.success('创建设备成功');
      setCreateModalVisible(false);
      form.resetFields();
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('创建设备失败');
    }
  };

  // 处理更新设备
  const handleUpdate = async (values) => {
    try {
      await updateDevice({
        ...values,
        id: currentRecord.id,
      });
      message.success('更新设备成功');
      setUpdateModalVisible(false);
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('更新设备失败');
    }
  };

  // 处理删除设备
  const handleDelete = async (id) => {
    try {
      await deleteDevice(id);
      message.success('删除设备成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('删除设备失败');
    }
  };

  // 处理更新设备状态
  const handleUpdateStatus = async (id, status) => {
    try {
      await updateDeviceStatus(id, status);
      message.success('更新设备状态成功');
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      message.error('更新设备状态失败');
    }
  };

  // 渲染设备类型标签
  const renderDeviceTypeTag = (type) => {
    const colorMap = {
      1: 'blue',
      2: 'green',
      3: 'orange',
      4: 'cyan',
      5: 'purple',
      6: 'magenta',
      7: 'gold',
      99: 'default',
    };
    
    const deviceType = deviceTypeOptions.find(item => item.value === type);
    return deviceType ? (
      <Tag color={colorMap[type] || 'default'}>
        {deviceType.label}
      </Tag>
    ) : '未知';
  };

  // 获取所有设备分组
  useEffect(() => {
    const fetchAllGroups = async () => {
      try {
        const res = await getDeviceGroupList({ pageSize: 100 });
        if (res.success && res.data) {
          // 获取每个分组的详细信息，包括设备计数
          const groupsWithDetails = await Promise.all(
            (res.data.data || []).map(async (group) => {
              try {
                const detailRes = await getDeviceGroupDetail(group.id);
                if (detailRes.success && detailRes.data) {
                  return detailRes.data;
                }
                return group;
              } catch (err) {
                console.error(`获取分组 ${group.id} 详情失败:`, err);
                return group;
              }
            })
          );
          setAllGroups(groupsWithDetails);
        }
      } catch (error) {
        console.error('获取设备分组失败:', error);
      }
    };

    fetchAllGroups();
  }, []);

  // 获取设备所属分组
  const fetchDeviceGroups = async (deviceId) => {
    setDeviceGroupsLoading(true);
    try {
      const response = await getGroupsByDevice(deviceId);
      if (response.success) {
        const groups = response.data || [];
        setCurrentDeviceGroups(groups);
        return groups;
      } else {
        message.error('获取设备分组失败');
      }
    } catch (error) {
      message.error('获取设备分组失败: ' + (error.message || '未知错误'));
    } finally {
      setDeviceGroupsLoading(false);
    }
    return [];
  };

  // 打开设备分组管理
  const openDeviceGroupsManagement = async (record) => {
    setCurrentRecord(record);
    setDeviceGroupsVisible(true);
    setDeviceGroupsLoading(true);
    
    try {
      const response = await getGroupsByDevice(record.id);
      if (response.success) {
        const groups = response.data || [];
        setCurrentDeviceGroups(groups);
        
        // 更新deviceGroupsMap - 确保使用对象形式
        setDeviceGroupsMap(prevMap => ({
          ...prevMap,
          [record.id]: groups
        }));
      } else {
        message.error('获取设备分组失败');
      }
    } catch (error) {
      message.error('获取设备分组失败: ' + (error.message || '未知错误'));
    } finally {
      setDeviceGroupsLoading(false);
    }
  };

  // 管理设备分组
  const handleManageGroups = async (deviceId, groupIds) => {
    try {
      // 获取当前分组IDs
      const currentGroupIds = currentDeviceGroups.map(group => group.id);
      
      // 需要添加的分组
      const groupsToAdd = groupIds.filter(id => !currentGroupIds.includes(id));
      
      // 需要移除的分组
      const groupsToRemove = currentGroupIds.filter(id => !groupIds.includes(id));
      
      // 添加到新分组
      if (groupsToAdd.length > 0) {
        for (const groupId of groupsToAdd) {
          await addDevicesToGroup(groupId, [deviceId]);
        }
      }
      
      // 从旧分组移除
      if (groupsToRemove.length > 0) {
        for (const groupId of groupsToRemove) {
          await removeDevicesFromGroup(groupId, [deviceId]);
        }
      }
      
      message.success('设备分组已更新');
      
      // 刷新分组信息
      const updatedGroups = await fetchDeviceGroups(deviceId);
      
      // 更新缓存
      if (updatedGroups) {
        setDeviceGroupsMap(prev => ({
          ...prev,
          [deviceId]: updatedGroups
        }));
      }
      
    } catch (error) {
      message.error('更新设备分组失败: ' + (error.message || '未知错误'));
    }
  };

  // 获取所有设备的分组信息
  const fetchAllDeviceGroups = async (deviceList) => {
    if (!deviceList || deviceList.length === 0) return;
    
    // 创建一个新的对象，避免直接修改状态
    const groupsMap = { ...deviceGroupsMap };
    const promises = [];
    
    // 只获取尚未缓存的设备分组
    const devicesToFetch = deviceList.filter(device => !groupsMap[device.id]);
    
    // 如果没有需要获取的设备，直接返回
    if (devicesToFetch.length === 0) return;
    
    // 显示加载提示，避免用户等待
    const loadingMessage = message.loading('正在加载设备分组信息...', 0);
    
    for (const device of devicesToFetch) {
      promises.push(
        getGroupsByDevice(device.id)
          .then(response => {
            if (response.success) {
              // 确保获取完整的分组对象，包含name而不仅是ID
              groupsMap[device.id] = response.data || [];
            }
          })
          .catch(error => {
            console.error(`获取设备 ${device.id} 的分组失败:`, error);
            groupsMap[device.id] = []; // 确保设置一个空数组以避免再次请求
          })
      );
    }
    
    try {
      await Promise.all(promises);
      // 更新状态
      setDeviceGroupsMap(groupsMap);
    } catch (error) {
      console.error('批量获取设备分组失败:', error);
    } finally {
      // 关闭加载提示
      loadingMessage();
    }
  };

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '设备编号',
      dataIndex: 'device_no',
      width: 120,
    },
    {
      title: '设备名称',
      dataIndex: 'device_name',
      width: 150,
    },
    {
      title: '设备类型',
      dataIndex: 'device_type',
      valueEnum: deviceTypeOptions.reduce((prev, curr) => {
        prev[curr.value] = { text: curr.label };
        return prev;
      }, {}),
      width: 120,
      render: (_, record) => renderDeviceTypeTag(record.device_type),
    },
    {
      title: '所属门店',
      dataIndex: 'store_id',
      hideInSearch: true,
      width: 150,
      render: (storeId) => {
        const store = stores.find(item => item.id === storeId);
        return store ? store.name : storeId;
      },
    },
    {
      title: '所属场地',
      dataIndex: 'venue_id',
      hideInSearch: true,
      width: 150,
      render: (roomId) => {
        const venue = venues.find(item => item.id === roomId);
        return venue ? venue.name : roomId;
      },
    },
    {
      title: '所属分组',
      dataIndex: 'groups',
      hideInSearch: true,
      width: 180,
      render: (_, record) => {
        // 从deviceGroupsMap中获取当前设备的分组信息
        const recordGroups = deviceGroupsMap[record.id] || [];
        
        return (
          <div style={{ display: 'flex', alignItems: 'center' }}>
            {recordGroups.length > 0 ? (
              <div style={{ marginRight: 8 }}>
                {recordGroups.slice(0, 2).map(group => (
                  <Tag color="blue" key={group.id} style={{ marginRight: 4, marginBottom: 4 }}>
                    {group.name || `分组${group.id}`}
                  </Tag>
                ))}
                {recordGroups.length > 2 && (
                  <Tag color="default">+{recordGroups.length - 2}</Tag>
                )}
              </div>
            ) : (
              <span style={{ color: '#999', marginRight: 8 }}>未分组</span>
            )}
            <a onClick={() => openDeviceGroupsManagement(record)}>
              <Tooltip title="管理分组">
                <TeamOutlined />
              </Tooltip>
            </a>
          </div>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: deviceStatusOptions.reduce((prev, curr) => {
        prev[curr.value] = { text: curr.label };
        return prev;
      }, {}),
      width: 100,
      render: (_, record) => renderStatusBadge(record.status),
    },
    {
      title: '最后在线时间',
      dataIndex: 'last_online',
      hideInSearch: true,
      width: 180,
      render: (text) => text ? new Date(text * 1000).toLocaleString() : '-',
    },
    {
      title: 'IP地址',
      dataIndex: 'ip_address',
      hideInSearch: true,
      width: 130,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            form.setFieldsValue(record);
            // 设置选中的门店ID，以便过滤场地
            setSelectedStoreId(record.store_id);
            if (record.store_id) {
              const storeVenues = venues.filter(venue => venue.store_id === record.store_id);
              setFilteredVenues(storeVenues);
            }
            setUpdateModalVisible(true);
          }}
        >
          <Tooltip title="编辑">
            <EditOutlined />
          </Tooltip>
        </a>,
        <a
          key="logs"
          onClick={() => handleViewLogs(record.id)}
        >
          <Tooltip title="日志">
            <HistoryOutlined />
          </Tooltip>
        </a>,
        <Dropdown
          key="status"
          overlay={
            <Menu>
              {deviceStatusOptions.map(option => (
                <Menu.Item key={option.value}>
                  <a onClick={() => handleUpdateStatus(record.id, option.value)}>
                    {option.label}
                  </a>
                </Menu.Item>
              ))}
            </Menu>
          }
        >
          <a>
            <Tooltip title="设置状态">
              <SettingOutlined />
            </Tooltip>
          </a>
        </Dropdown>,
        <Popconfirm
          key="delete"
          title="确定要删除这个设备吗？"
          onConfirm={() => handleDelete(record.id)}
          okText="确定"
          cancelText="取消"
        >
          <a>
            <Tooltip title="删除">
              <DeleteOutlined />
            </Tooltip>
          </a>
        </Popconfirm>,
      ],
    },
  ];

  // 设备表单字段
  const formFields = [
    {
      name: 'device_no',
      label: '设备编号',
      rules: [{ required: true, message: '请输入设备编号' }],
      component: <Input placeholder="请输入设备编号" />,
    },
    {
      name: 'device_name',
      label: '设备名称',
      rules: [{ required: true, message: '请输入设备名称' }],
      component: <Input placeholder="请输入设备名称" />,
    },
    {
      name: 'device_type',
      label: '设备类型',
      rules: [{ required: true, message: '请选择设备类型' }],
      component: (
        <Select placeholder="请选择设备类型">
          {deviceTypeOptions.map(option => (
            <Select.Option key={option.value} value={option.value}>
              {option.label}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      name: 'store_id',
      label: '所属门店',
      rules: [{ required: true, message: '请选择所属门店' }],
      component: (
        <Select 
          placeholder="请选择所属门店" 
          onChange={handleStoreChange}
          showSearch
          optionFilterProp="children"
          filterOption={(input, option) =>
            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }
        >
          {stores.map(store => (
            <Select.Option key={store.id} value={store.id}>
              {store.name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      name: 'venue_id',
      label: '所属场地',
      rules: [{ required: false, message: '请选择所属场地' }],
      component: (
        <Select 
          placeholder="请选择所属场地"
          showSearch
          optionFilterProp="children"
          filterOption={(input, option) =>
            option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }
          disabled={!selectedStoreId}
        >
          {filteredVenues.map(venue => (
            <Select.Option key={venue.id} value={venue.id}>
              {venue.name}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      name: 'status',
      label: '状态',
      rules: [{ required: true, message: '请选择设备状态' }],
      component: (
        <Select placeholder="请选择设备状态">
          {deviceStatusOptions.map(option => (
            <Select.Option key={option.value} value={option.value}>
              {option.label}
            </Select.Option>
          ))}
        </Select>
      ),
    },
    {
      name: 'ip_address',
      label: 'IP地址',
      component: <Input placeholder="请输入IP地址" />,
    },
    {
      name: 'mac_address',
      label: 'MAC地址',
      component: <Input placeholder="请输入MAC地址" />,
    },
    {
      name: 'api_key',
      label: 'API密钥',
      component: <Input placeholder="请输入API密钥" />,
    },
    {
      name: 'api_endpoint',
      label: 'API接口地址',
      component: <Input placeholder="请输入API接口地址" />,
    },
    {
      name: 'manufacturer',
      label: '制造商',
      component: <Input placeholder="请输入制造商" />,
    },
    {
      name: 'model',
      label: '型号',
      component: <Input placeholder="请输入型号" />,
    },
    {
      name: 'firmware',
      label: '固件版本',
      component: <Input placeholder="请输入固件版本" />,
    },
    {
      name: 'description',
      label: '描述',
      component: <Input.TextArea rows={4} placeholder="请输入设备描述" />,
    },
  ];

  // 批量操作选项
  const batchOperationMenu = (
    <Menu>
      <Menu.Item key="delete" onClick={handleBatchDelete}>
        <DeleteOutlined /> 批量删除
      </Menu.Item>
      <Menu.SubMenu key="status" title="批量修改状态">
        {deviceStatusOptions.map(option => (
          <Menu.Item key={`status-${option.value}`} onClick={() => handleBatchUpdateStatus(option.value)}>
            {option.label}
          </Menu.Item>
        ))}
      </Menu.SubMenu>
    </Menu>
  );

  return (
    <PageContainer>
      <ProTable
        headerTitle="设备列表"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
          defaultCollapsed: false,
        }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="create"
            onClick={() => {
              form.resetFields();
              setSelectedStoreId(null);
              setFilteredVenues([]);
              setCreateModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          <Dropdown overlay={batchOperationMenu} key="batchOperation" disabled={selectedRowKeys.length === 0}>
            <Button>
              批量操作 <DownOutlined />
            </Button>
          </Dropdown>,
          <Button key="export" onClick={() => message.info('导出功能开发中')}>
            <ExportOutlined /> 导出
          </Button>,
          <Button key="import" onClick={() => message.info('导入功能开发中')}>
            <ImportOutlined /> 导入
          </Button>,
        ]}
        request={async (params) => {
          // 转换查询参数
          const { current, pageSize, ...rest } = params;
          const query = {
            page: current,
            pageSize,
            ...rest,
          };
          
          try {
            const response = await getDeviceList(query);
            
            // 调试输出
            console.log('设备列表响应:', response);
            
            if (response.success) {
              // 获取设备分组信息
              if (response.data && response.data.data && response.data.data.length > 0) {
                fetchAllDeviceGroups(response.data.data);
              }
              return {
                data: response.data.data || [],
                success: true,
                total: response.data.total || 0,
              };
            } else {
              message.error('获取设备列表失败: ' + (response.message || '未知错误'));
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          } catch (error) {
            console.error('获取设备列表出错:', error);
            message.error('获取设备列表失败: ' + (error.message || '未知错误'));
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
        scroll={{ x: 1300 }}
      />

      {/* 创建设备表单 */}
      <Modal
        title="创建设备"
        visible={createModalVisible}
        onCancel={() => setCreateModalVisible(false)}
        footer={null}
        width={720}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreate}
        >
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
            {formFields.map(field => (
              <Form.Item
                key={field.name}
                name={field.name}
                label={field.label}
                rules={field.rules}
                style={field.name === 'description' ? { gridColumn: 'span 2' } : {}}
              >
                {field.component}
              </Form.Item>
            ))}
          </div>
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setCreateModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit">创建</Button>
            </Space>
          </div>
        </Form>
      </Modal>

      {/* 更新设备表单 */}
      <Modal
        title="编辑设备"
        visible={updateModalVisible}
        onCancel={() => setUpdateModalVisible(false)}
        footer={null}
        width={720}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleUpdate}
        >
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px' }}>
            {formFields.map(field => (
              <Form.Item
                key={field.name}
                name={field.name}
                label={field.label}
                rules={field.rules}
                style={field.name === 'description' ? { gridColumn: 'span 2' } : {}}
              >
                {field.component}
              </Form.Item>
            ))}
          </div>
          <div style={{ textAlign: 'right' }}>
            <Space>
              <Button onClick={() => setUpdateModalVisible(false)}>取消</Button>
              <Button type="primary" htmlType="submit">更新</Button>
            </Space>
          </div>
        </Form>
      </Modal>

      {/* 设备日志抽屉 */}
      <Drawer
        title="设备操作日志"
        placement="right"
        width={600}
        onClose={() => setLogDrawerVisible(false)}
        visible={logDrawerVisible}
      >
        {deviceLogs.length > 0 ? (
          <div>
            {deviceLogs.map(log => (
              <div key={log.id} style={{ borderBottom: '1px solid #f0f0f0', padding: '16px 0' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Tag color="blue">{log.action}</Tag>
                  <span style={{ color: '#999' }}>
                    {new Date(log.created_at * 1000).toLocaleString()}
                  </span>
                </div>
                <div style={{ margin: '8px 0' }}>{log.detail}</div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{ textAlign: 'center', padding: '30px 0', color: '#999' }}>
            暂无日志记录
          </div>
        )}
      </Drawer>

      {/* 设备分组管理抽屉 */}
      <Drawer
        title={`管理设备分组: ${currentRecord.device_name || ''}`}
        width={500}
        placement="right"
        onClose={() => setDeviceGroupsVisible(false)}
        visible={deviceGroupsVisible}
      >
        <div style={{ marginBottom: 16 }}>
          <h4>当前所属分组:</h4>
          {deviceGroupsLoading ? (
            <div>加载中...</div>
          ) : currentDeviceGroups.length > 0 ? (
            <div style={{ marginBottom: 16 }}>
              {currentDeviceGroups.map(group => (
                <Tag color="blue" key={group.id} style={{ margin: '0 8px 8px 0' }}>
                  {group.name || `分组${group.id}`}
                </Tag>
              ))}
            </div>
          ) : (
            <div>该设备尚未分配到任何分组</div>
          )}
        </div>
        
        <Divider />
        
        <Form layout="vertical">
          <Form.Item label="添加到分组">
            <Select
              mode="multiple"
              placeholder="选择设备分组"
              onChange={(values) => handleManageGroups(currentRecord.id, values)}
              value={currentDeviceGroups.map(g => g.id)}
              style={{ width: '100%' }}
              loading={deviceGroupsLoading}
              optionLabelProp="label"
            >
              {allGroups.map(group => (
                <Select.Option key={group.id} value={group.id} label={group.name || `分组${group.id}`}>
                  {group.name || `分组${group.id}`}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          
          <Button 
            type="primary" 
            onClick={() => {
              // 跳转到设备分组页面，方便用户创建新分组
              window.location.href = '/device/group';
            }}
          >
            管理设备分组
          </Button>
        </Form>
      </Drawer>
    </PageContainer>
  );
};

export default DeviceList;